require 'rubygems'
require 'jdbc_adapter'
require 'active_record'
require 'java'
require 'hazelcast.jar'
require 'app/models/cpu'
require 'app/models/sysinfo'
Dir["lib/sigar-bin/lib/*.jar"].each { |jar| require jar }
Dir["lib/*.jar"].each { |jar| require jar }

import com.hazelcast.core.Hazelcast
import com.hazelcast.core.MembershipListener
import com.hazelcast.core.MembershipEvent

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.SigarException;

import java.util.Map
import java.util.Collection

cluster = Hazelcast.getCluster();
puts "I am an agent"

map_cpu = Hazelcast.get_map "cpu"
map_sys_info = Hazelcast.get_map "sysinfo"

sigar = Sigar.new
infos = sigar.cpu_info_list
si = Sysinfo.new
si.cpu_num = infos.length
mem = sigar.mem
swap = sigar.swap
si.mem_total = (mem.total / 1024)
si.mem_used = (mem.used / 1024).to_s
si.mem_free = (mem.free/ 1024).to_s
si.swap_total = (swap.total / 1024).to_s
si.swap_used = (swap.used / 1024).to_s
si.swap_free = (swap.free/ 1024).to_s
si.ram = mem.ram.to_s
si_raw = Marshal.dump(si)
map_sys_info.put("1", si_raw)

n = 1
infos.each do |info|
  cpu = Cpu.new
  cpu.vendor = info.vendor
  cpu.model = info.model
  cpu.mhz = info.mhz.to_s
  cpu.cache_size = info.cache_size.to_s
  cpu_raw = Marshal.dump(cpu)
  map_cpu.put(n.to_s, cpu_raw)
  n = n + 1
end


#cpu1 = map_cpu.get("1")
#cpu1 = Marshal.load(cpu1)

line = 'Cluster time ' + cluster.get_cluster_time.to_s
puts line

while !line.eql? 'quit'
  print '> '
  line = gets.chop
  # puts "Command: #{line}"
end

Process.exit

cluster.add_membership_listener {|event| 
  member = event.getMember
  address = member.get_inet_address.to_s
  port = member.get_port
  address = address.gsub("/", "")
  type = event.get_event_type
  type_text = "NOT_DEFINED"
  if type == 1
    type_text = "MEMBER_ADDED"
  end
  if type == 3
    type_text = "MEMBER_REMOVED"
  end
  
  puts "Node: " + address + " status " + type_text
}
